<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Models\User;
use DB;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Validator;

class RoleController extends Controller {
	private $role_flag;
	private $user;
	public function __construct() {
		if (\Auth::guard('api')->check()) {
			$getUser = \Auth::guard('api')->user();
			$user = User::find($getUser->id);
			if (!$this->getDevice()) {
				//app
				$user->company_id = $user->appcompany_id;
			}
			$this->user = $user;
			$company = \App\Models\Company::find($this->user->company_id);
			$this->role_flag = $company->role_flag;
		}
	}

	public function all(Request $request) {
		$data = Role::where(['guard_name' => $this->role_flag, 'status' => 0])->orderBy('type')->orderBy('is_delete', 'desc')->orderBy('id', 'desc')->select('id', 'name', 'remarks', 'type', 'is_delete')->get();
		return $this->respond('get_ok', $data);
	}
	//新增角色
	public function add(Request $request) {
		$user = $this->user;
		$user->guard_name = $this->role_flag;
		$roleType = $request->input('roleType');
		$staff = \App\Models\Staff::where(['status' => 0, 'mobile' => $user->mobile, 'role_status' => 1])->first();
		if ($roleType == 1) {
			if (!empty($staff) && $staff->company_id == $user->company_id) {
				if (!$user->can('role_add') && !$user->hasRole('管理员')) {
					return $this->respond('no_auth');
				}
			} else {
				if (!$user->can('role_add')) {
					return $this->respond('no_auth');
				}
			}
			return $this->respond('op_ok');
		}
		if (!empty($staff) && $staff->company_id == $user->company_id) {
			if (!$user->can('role_add') && !$user->hasRole('管理员')) {
				return $this->respond('no_auth');
			}
		} else {
			if (!$user->can('role_add')) {
				return $this->respond('no_auth');
			}
		}
		$validator = Validator::make($request->all(),
			['name' => 'required|max:20', 'remarks' => 'sometimes|max:120'],
			['name.required' => '角色名称必须填写', 'name.max' => '角色名称最多20个字符', 'remarks.max' => '备注最多120个字符']);
		if ($validator->fails()) {
			return response()->json(['code' => 500, 'msg' => $validator->errors()->first()]);
		}
		$m = new Role();
		$name = $request->input('name');
		$data = $m::where(['name' => $name, 'guard_name' => $this->role_flag, 'status' => 0])->first();
		if (!empty($data)) {
			return response()->json(['code' => 500, 'msg' => '角色名称不能重复']);
		}
		$role_flag = $this->role_flag;
		$remarks = $request->input('remarks');
		$result = Role::insert(['name' => $name, 'guard_name' => $role_flag, 'remarks' => $remarks, 'created_at' => time(), 'updated_at' => time()]);
		if ($result) {
			return $this->respond('add_ok');
		}
		return $this->respond('add_error');
	}
	//更新角色
	public function put(Request $request, $id) {
		$user = $this->user;
		$user->guard_name = $this->role_flag;
		$staff = \App\Models\Staff::where(['status' => 0, 'mobile' => $user->mobile, 'role_status' => 1])->first();
		if (!empty($staff) && $staff->company_id == $user->company_id) {
			if (!$user->can('role_edit') && !$user->hasRole('管理员')) {
				return $this->respond('no_auth');
			}
		} else {
			if (!$user->can('role_edit')) {
				return $this->respond('no_auth');
			}
		}
		$validator = Validator::make($request->all(),
			['name' => 'required|max:20', 'remarks' => 'sometimes|max:120'],
			['name.required' => '角色名称必须填写', 'name.max' => '角色名称最多20个字符', 'remarks.max' => '备注最多120个字符']);
		if ($validator->fails()) {
			return response()->json(['code' => 500, 'msg' => $validator->errors()->first()]);
		}
		$m = new Role();
		$model = $m::find($id);
		if (empty($model)) {
			return $this->respond('get_error');
		}
		if ($model->is_delete == 2) {
			return response()->json(['code' => 500, 'msg' => '系统创建的角色不允许更新操作']);
		}
		$name = $request->input('name');
		$data = $m::where(['name' => $name, 'guard_name' => $this->role_flag, 'status' => 0])->where('id', '!=', $id)->first();
		if (!empty($data)) {
			return response()->json(['code' => 500, 'msg' => '角色名称不能重复']);
		}
		$name = $name;
		$remarks = $request->input('remarks');
		$result = Role::where('id', $id)->update(['name' => $name, 'remarks' => $remarks, 'updated_at' => time()]);
		if ($result) {
			return $this->respond('update_ok');
		}
		return $this->respond('update_error');
	}
	//删除角色
	public function remove(Request $request, $id) {
		$user = $this->user;
		$user->guard_name = $this->role_flag;
		$staff = \App\Models\Staff::where(['status' => 0, 'mobile' => $user->mobile, 'role_status' => 1])->first();
		if (!empty($staff) && $staff->company_id == $user->company_id) {
			if (!$user->can('role_remove') && !$user->hasRole('管理员')) {
				return $this->respond('no_auth');
			}
		} else {
			if (!$user->can('role_remove')) {
				return $this->respond('no_auth');
			}
		}
		$m = new Role();
		$model = $m::find($id);
		if (empty($model)) {
			return $this->respond('get_error');
		}
		if ($model->is_delete == 2) {
			return response()->json(['code' => 500, 'msg' => '系统创建的角色不允许删除操作']);
		}
		$check_per = \DB::table('role_has_permissions')->where('role_id', $id)->first();
		if (!empty($check_per)) {
			return response()->json(['code' => 500, 'msg' => '请先删除该角色下的权限']);
		}
		$check_role = \DB::table('model_has_roles')->where('role_id', $id)->first();
		if (!empty($check_role)) {
			return response()->json(['code' => 500, 'msg' => '请先删除该角色下的用户']);
		}
		$result = Role::where('id', $id)->update(['status' => 1, 'updated_at' => time()]);
		if ($result) {
			return $this->respond('delete_ok');
		}
		return $this->respond('delete_error');
	}

	//获取权限
	public function getRolePermission($id) {
		if (empty($id)) {
			return response()->json(['code' => 500, 'msg' => '角色id不能为空']);
		}
		$data = Permission::where(['guard_name' => $this->role_flag, 'status' => 0])->select('id', 'alias')->get()->toArray();
		$info[0]['name'] = '人才';
		$info[1]['name'] = '职位';
		$info[2]['name'] = '权限管理';
		$info[3]['name'] = '设置';
		$info[4]['name'] = '公共流程权限';
		$info[5]['name'] = '自定义流程';
		$info[0]['item'] = array_slice($data, 0, 3);
		$info[1]['item'] = array_slice($data, 3, 3);
		$info[2]['item'] = array_slice($data, 6, 5);
		$info[3]['item'] = array_slice($data, 11, 10);
		$info[4]['item'] = array_slice($data, 21, 10);
		$info[5]['item'] = array_slice($data, 31);
		$item['list'] = $info;
		$ids = \DB::table('role_has_permissions')->where('role_id', $id)->pluck('permission_id');
		$item['ids'] = $ids;
		return $this->respond('get_ok', $item);

	}
	//分配权限
	public function editRolePermission(Request $request, $id) {
		$user = $this->user;
		$user->guard_name = $this->role_flag;
		$staff = \App\Models\Staff::where(['status' => 0, 'mobile' => $user->mobile, 'role_status' => 1])->first();
		if (!empty($staff) && $staff->company_id == $user->company_id) {
			if (!$user->can('role_permission') && !$user->hasRole('管理员')) {
				return $this->respond('no_auth');
			}
		} else {
			if (!$user->can('role_permission')) {
				return $this->respond('no_auth');
			}
		}
		if (empty($id)) {
			return response()->json(['code' => 500, 'msg' => '角色id不能为空']);
		}

		$id_arr = $request->input('idArr');
		if (!empty($id_arr) && !is_array($id_arr)) {
			return response()->json(['code' => 500, 'msg' => '权限数组格式不正确']);
		}
		if (empty($id_arr)) {
			$id_arr = [];
		}
		$getRole = Role::where(['id' => $id, 'status' => 0])->first();
		if (empty($getRole)) {
			$this->respond('empty_error');
		}
		$getPermission = Permission::whereIn('id', $id_arr)->get();
		$result = $getRole->syncPermissions($getPermission);
		if ($result) {
			return $this->respond('op_ok');
		}
		return $this->respond('op_error');
	}
	//获取角色用户
	public function getRoleUser(Request $request, $id) {
		if (empty($id)) {
			return response()->json(['code' => 500, 'msg' => '角色id不能为空']);
		}
		$company_id = $this->user->company_id;
		$name = $request->input('name');
		$position = $request->input('position');
		$deptName = $request->input('deptName');
		$query = DB::table('staff as b')
			->join('users as a', 'b.user_id', '=', 'a.id')
			->join('departments as c', 'b.dept_id', '=', 'c.id')
			->where(['b.company_id' => $company_id, 'a.status' => 0, 'b.status' => 0])
			->where('b.user_id', '!=', 0)->where('a.company_id', '!=', 0);

		if (!empty($name) || $name == '0') {
			$query = $query->where('a.name', 'like', '%' . $name . '%');
		}
		if (!empty($deptName) || $deptName == '0') {
			$query = $query->where('c.name', 'like', '%' . $deptName . '%');
		}
		if (!empty($position) || $position == '0') {
			$query = $query->where('b.position', 'like', '%' . $position . '%');
		}
		$data = $query->select('a.id', 'b.position', 'a.name', 'a.mobile', 'c.name as dept_name')->get();
		$item['item'] = $data;
		$ids = DB::table('model_has_roles')->where('role_id', $id)->pluck('model_id');
		$item['ids'] = $ids;
		return $this->respond('get_ok', $item);
	}
	//给角色分配用户
	public function editRoleUser(Request $request, $id) {
		$user = $this->user;
		$user->guard_name = $this->role_flag;
		$staff = \App\Models\Staff::where(['status' => 0, 'mobile' => $user->mobile, 'role_status' => 1])->first();
		if (!empty($staff) && $staff->company_id == $user->company_id) {
			if (!$user->can('role_user') && !$user->hasRole('管理员')) {
				return $this->respond('no_auth');
			}
		} else {
			if (!$user->can('role_user')) {
				return $this->respond('no_auth');
			}
		}
		if (empty($id)) {
			return response()->json(['code' => 500, 'msg' => '角色id不能为空']);
		}
		$getRole = Role::find($id);
		if (empty($getRole)) {
			return $this->respond('get_error');
		}
		$id_arr = $request->input('idArr');
		if (!empty($id_arr) && !is_array($id_arr)) {
			return response()->json(['code' => 500, 'msg' => '用户数组格式不正确']);
		}
		if (empty($id_arr)) {
			$id_arr = [];
		}
		$roles = DB::table('model_has_roles')->where('role_id', $id)->get();

		$getUser = [];
		if (!empty($id_arr)) {
			$getUser = User::whereIn('id', $id_arr)->get();
		}
		//开启事务
		DB::beginTransaction();
		try {
			//中间逻辑代码
			if (!empty($roles)) {
				//删除用户已有的角色

				foreach ($roles as $k => $val) {

					$get_role_id = $val->model_id;
					$role_user = User::where(['status' => 0, 'id' => $get_role_id])->first();
					if (!empty($role_user->company_id)) {
						$company = Company::where(['id' => $role_user->company_id, 'status' => 0])->first();
						$check_roles = Role::where(['name' => '管理员', 'type' => 1, 'is_delete' => 2, 'guard_name' => $this->role_flag])->first();
						if ($check_roles->id != $get_role_id) {
							//去除超级管理员角色判断
							$role_user->guard_name = $company->role_flag;
							$role_user->removeRole($getRole); //移除角色
						}
					}
				}
			}
			if (!empty($getUser)) {
				//更新用户分配新的权限
				foreach ($getUser as $key => $value) {
					$value->guard_name = $this->role_flag;
					$value->assignRole($getRole); //添加权限
				}
			}
			DB::commit();
			return $this->respond('op_ok');
		} catch (\Exception $e) {
			//接收异常处理并回滚
			DB::rollBack();
			dd($e);
			return $this->respond('op_error');
		}
	}
}
